import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Match } from './matches.entity';
import { User } from '../users/users.entity';

@Injectable()
export class MatchService {
  private readonly logger = new Logger(MatchService.name);

  constructor(
    @InjectRepository(Match)
    private matchRepository: Repository<Match>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  // 查找匹配的用户
  async findMatches(userId: number, preferences: any): Promise<User[]> {
    this.logger.log(`查找匹配用户，用户ID: ${userId}`);

    // 构建查询条件
    let query = this.userRepository
      .createQueryBuilder('user')
      .where('user.id != :userId', { userId });

    // 应用国家筛选条件
    if (preferences.nationality && preferences.nationality !== '') {
      query = query.andWhere('user.from LIKE :nationality', {
        nationality: `%${preferences.nationality}%`,
      });
    }

    // 应用性别筛选条件
    if (
      preferences.gender &&
      preferences.gender !== '' &&
      preferences.gender !== '不限'
    ) {
      query = query.andWhere('user.gender = :gender', {
        gender: preferences.gender === '男性' ? 'male' : 'female',
      });
    }

    // 应用年龄范围筛选条件
    if (preferences.ageRange) {
      if (preferences.ageRange.min) {
        const minBirthYear =
          new Date().getFullYear() - preferences.ageRange.min;
        const minBirthDate = new Date(minBirthYear, 0, 1);
        query = query.andWhere('user.birthday <= :minBirthDate', {
          minBirthDate,
        });
      }

      if (preferences.ageRange.max) {
        const maxBirthYear =
          new Date().getFullYear() - preferences.ageRange.max;
        const maxBirthDate = new Date(maxBirthYear, 11, 31);
        query = query.andWhere('user.birthday >= :maxBirthDate', {
          maxBirthDate,
        });
      }
    }

    // 应用语言筛选条件
    if (preferences.languages && preferences.languages.length > 0) {
      // 这里假设用户资料中有一个languages字段存储用户的语言
      // 根据实际数据结构可能需要调整
      query = query.andWhere('user.languages && :languages', {
        languages: preferences.languages,
      });
    }

    // 应用排除同国籍筛选条件
    if (preferences.hideSameNationality && preferences.nationality) {
      query = query.andWhere('user.from NOT LIKE :nationality', {
        nationality: `%${preferences.nationality}%`,
      });
    }

    // 应用排除特定国籍筛选条件
    if (
      preferences.excludedNationalities &&
      preferences.excludedNationalities.length > 0
    ) {
      preferences.excludedNationalities.forEach(
        (excludedNationality: string) => {
          query = query.andWhere('user.from NOT LIKE :excludedNationality', {
            excludedNationality: `%${excludedNationality}%`,
          });
        },
      );
    }

    // 不再考虑地理位置因素，只根据筛选条件匹配
    const users = await query.limit(10).getMany();

    this.logger.log(`找到 ${users.length} 个匹配用户`);
    return users;
  }

  // 处理滑动操作
  async handleSwipe(
    userId: number,
    targetUserId: number,
    action: string,
  ): Promise<any> {
    // 验证输入参数
    if (!userId || !targetUserId) {
      throw new BadRequestException('用户ID不能为空');
    }

    if (userId === targetUserId) {
      throw new BadRequestException('不能对自己进行操作');
    }

    if (!['like', 'dislike'].includes(action)) {
      throw new BadRequestException('无效的操作类型');
    }

    this.logger.log(
      `处理滑动操作，用户ID: ${userId}, 目标用户ID: ${targetUserId}, 操作: ${action}`,
    );

    if (action === 'like') {
      // 检查是否双向喜欢（匹配）
      const existingMatch = await this.matchRepository.findOne({
        where: [
          { userId: targetUserId, matchedUserId: userId },
          { userId: userId, matchedUserId: targetUserId },
        ],
      });

      if (existingMatch) {
        // 已存在匹配，不需要重复创建
        return {
          matched: false,
          message: '匹配已存在',
        };
      }

      // 创建单向喜欢记录
      const match = this.matchRepository.create({
        userId: userId,
        matchedUserId: targetUserId,
        matchType: 'manual',
        status: 'liked',
      });

      await this.matchRepository.save(match);

      // 检查对方是否也喜欢了当前用户
      const reverseMatch = await this.matchRepository.findOne({
        where: {
          userId: targetUserId,
          matchedUserId: userId,
        },
      });

      if (reverseMatch) {
        // 双向匹配成功
        this.logger.log(
          `匹配成功，用户ID: ${userId}, 匹配用户ID: ${targetUserId}`,
        );
        return {
          matched: true,
          matchId: match.id,
          matchedUserId: targetUserId,
          message: '匹配成功！',
        };
      }

      return {
        matched: false,
        message: '喜欢已记录',
      };
    }

    // dislike 操作不需要特殊处理
    return {
      matched: false,
      message: '不喜欢已记录',
    };
  }

  // 获取用户的匹配列表
  async getUserMatches(userId: number): Promise<User[]> {
    this.logger.log(`获取用户匹配列表，用户ID: ${userId}`);

    const matches = await this.matchRepository
      .createQueryBuilder('match')
      .leftJoinAndSelect('match.matchedUser', 'matchedUser')
      .where('match.userId = :userId AND match.status = :status', {
        userId,
        status: 'active',
      })
      .getMany();

    return matches.map((match) => match.matchedUser);
  }

  // 获取新匹配列表
  async getNewMatches(userId: number): Promise<Match[]> {
    this.logger.log(`获取新匹配列表，用户ID: ${userId}`);

    // 获取最近的匹配记录
    const matches = await this.matchRepository
      .createQueryBuilder('match')
      .leftJoinAndSelect('match.matchedUser', 'matchedUser')
      .where('match.userId = :userId AND match.status = :status', {
        userId,
        status: 'active',
      })
      .orderBy('match.matchedAt', 'DESC')
      .limit(20)
      .getMany();

    return matches;
  }

  // 保存用户筛选条件
  async saveUserFilters(userId: number, filters: any): Promise<void> {
    this.logger.log(`保存用户筛选条件，用户ID: ${userId}`);
    // 获取用户当前的数据
    const user = await this.userRepository.findOne({
      where: { id: userId },
    });

    if (user) {
      // 更新用户的筛选条件到数据库，保留原有的assets中的其他数据
      await this.userRepository.update(userId, {
        assets: {
          ...(user.assets || {}),
          filters: filters,
        },
      });
    }
  }

  // 获取用户筛选条件
  async getUserFilters(userId: number): Promise<any> {
    this.logger.log(`获取用户筛选条件，用户ID: ${userId}`);
    // 从数据库中获取用户的筛选条件
    const user = await this.userRepository.findOne({
      where: { id: userId },
    });

    if (user && user.assets && user.assets.filters) {
      return user.assets.filters;
    }

    // 返回空的默认筛选条件
    return {
      location: {
        latitude: 0,
        longitude: 0,
        address: '',
        roaming: false,
      },
      gender: '',
      ageRange: {
        min: 0,
        max: 0,
      },
      languages: [],
      nationality: '',
      hideSameNationality: false,
      excludedNationalities: [],
    };
  }
}